package com.jiliason.segmentation.doMain;

import com.jiliason.segmentation.constant.enums.Err;
import com.jiliason.segmentation.exception.ACSysException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Component
public class ServiceCache implements ApplicationContextAware {

    private static final List<AbstractService> CACHE = new LinkedList<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, AbstractService> beans = applicationContext.getBeansOfType(AbstractService.class);
        CACHE.addAll(beans.values());
    }

    public AbstractService getProcessor(String serviceTag, String serviceId) throws ACSysException {
        for (AbstractService service : CACHE) {
            if (service.getProcessor(serviceTag, serviceId)) {
                return service;
            }
        }
        throw new ACSysException(serviceTag + serviceId + " : no find.", Err.A);
    }
}
